package com.uestc.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.uestc.util.Log;

public interface ServletBase {

	/**
	 * 这个方法在一个Servlet中只能被调用一次，可将msg拼接好后，再调用
	 * 
	 * @param response
	 * @param msg
	 */
	default public void writeMessage(HttpServletResponse response, String msg) {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			Log.logException(e);
			return;
		}
		pw.write(msg);
		pw.flush();
		pw.close();
	}

	/**
	 * 判断参数是否为null或空，为空则返回true
	 * 
	 * @param arg
	 * @return
	 */
	default public boolean isArgumentNullOrEmpty(String... args) {
		for (String arg : args) {
			if (arg == null || arg.equals(""))
				return true;
		}
		return false;
	}

	/**
	 * 拼接生成请求参数组成的字符串：如name=sunflower.jpg&hash=Fn6qeQi4VDLQ347NiRm-RlQx_4O2&
	 * location=Shanghai&price=1500.00&uid=123
	 * 
	 * @param request
	 * @return
	 */
	default public String getRequestString(HttpServletRequest request) {
		InputStream is = null;
		String content = null;
		try {
			is = request.getInputStream();
			content = IOUtils.toString(is);
			System.out.println(content);
			return content;
		} catch (IOException e) {
			e.printStackTrace();
		}

		StringBuilder requestBody = new StringBuilder();
		Map<String, String[]> requestMap = request.getParameterMap();
		for (Map.Entry<String, String[]> entry : requestMap.entrySet()) {
			requestBody.append(entry.getKey());
			requestBody.append("=");
			requestBody.append(entry.getValue()[0]);
			requestBody.append("&");
		}
		String requestString = requestBody.substring(0, requestBody.length() - 1);
		return requestString;
	}

	default public String getParameter(HttpServletRequest request, String param) {
		return request.getParameter(param);
	}
}
